<template>
    <div class="container">
        <el-input v-model="searchData.userAccount" placeholder="账号" class="handle-input mr10"></el-input>
        <el-input v-model="searchData.userName" placeholder="姓名" class="handle-input mr10"></el-input>
        <el-button type="primary" :icon="Search" @click="searchUser">搜索</el-button>
        <el-button type="primary" :icon="Plus" @click="handleClickAddButton">新增</el-button>
        <el-table :data="allUserList" style="height: 600px; width: 100%;margin-top: 2%" class="table">
            <el-table-column label="账号" prop="account" />
            <el-table-column label="姓名" prop="name" />
            <el-table-column label="电话" prop="phone" />
            <el-table-column label="角色" prop="role" />
            <el-table-column label="状态" prop="status" />
            <el-table-column label="备注" prop="note" />
            <el-table-column label="操作" prop="$1">
                <template #default="scope">
                    <el-button size="small" @click="handleClickEditButton(scope)"
                    >编辑</el-button
                    >
                    <el-button
                        size="small"
                        type="danger"
                        @click="handleDelete(scope.$index, scope.row)"
                    >删除</el-button
                    >
                </template>
            </el-table-column>
        </el-table>
        <!--新增或编辑用户界面-->
        <el-dialog
            v-model="dialogVisible"
            :title="titleName"
            width="30%"
            @close="resetForm(ruleFormRef)"
        >
            <el-form
                ref="ruleFormRef"
                :model="ruleForm"
                :rules="rules"
                label-width="120px"
                class="demo-ruleForm"
                status-icon
            >
                <el-form-item label="账号" prop="account">
                    <el-input v-model="ruleForm.account" :disabled="inputDisabled"/>
                </el-form-item>
                <el-form-item label="用户名" prop="name">
                    <el-input v-model="ruleForm.name" />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input
                        v-model="ruleForm.password"
                        type="password"
                        placeholder="请输入账号密码"
                        show-password
                    />
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                    <el-input v-model="ruleForm.phone" />
                </el-form-item>
                <el-form-item label="角色" prop="role">
                    <el-select
                        v-model="ruleForm.role"
                        multiple
                        placeholder="请选择角色"
                        style="width: 240px"
                    >
                        <el-option
                            v-for="item in roleSet"
                            :key="item.roleId"
                            :label="item.roleName"
                            :value="item.roleId"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="state">
                    <el-radio-group v-model="ruleForm.state">
                        <el-radio label="1">启用</el-radio>
                        <el-radio label="0">停用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" prop="note">
                    <el-input v-model="ruleForm.note" type="textarea" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleClickSubmit">
                        {{ submitButton }}
                    </el-button>
                    <el-button @click="dialogVisible = false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import {reactive, ref, computed, nextTick, onMounted} from 'vue'
import type { FormInstance, FormRules, ElMessageBox, ElForm } from 'element-plus'
import {Plus, Search} from "@element-plus/icons-vue";
import API from "../utils/axios";
import {ElMessage} from "element-plus";

// 获取所有用户列表数据
const getAllUserInfo = () => {
    API.post('/UserController/searchAllUser')
        .then((res) => {
            const userList  = res.data.data.map((item : any) => {
                let accountStatus  = '';
                if (item.userStatus == 0){
                    accountStatus = '禁用';
                }else{
                    accountStatus = '启用';
                }
                return { account : item.userAccount, name: item.userName, phone : item.userPhone, password : item.userPassword,
                    role : item.roleNameSet, status : accountStatus, note : item.userNote}
            })
            allUserList.value = userList;
        })
        .catch((err) => {
            return err
        })
}

// 用户列表
const allUserList = ref([]);
onMounted(() => {
    // 使用async函数异步获取数据
    (async () =>{
        try {
            getAllUserInfo();
        }catch (err){
            console.log(err)
        }
    })()
})

// 提交按钮事件
const handleClickSubmit =async () => {
      await addEditUser();
      await getAllUserInfo();
    dialogVisible.value = false;
}

// 新增按钮事件
const handleClickAddButton = () => {
    controls('add');
    getRoleInfo();
}

// 编辑按钮事件
const handleClickEditButton = (scope : any) => {
    controls('edit');
    handleEdit(scope.$index, scope.row);
    getRoleInfo();
}

// 删除按钮事件
const handleDelete = (index: number, row: any) => {
    const formData = new FormData();
    formData.append('userAccount', row.account);
    API.post("/UserController/deleteUser", formData)
        .then((res) => {
            if (res.data.data == "删除成功"){
                ElMessage("删除成功！");
            }else {
                ElMessage("删除失败");
            }
        })
        .catch((err) => {return err})
    // 删除列表并刷新
    allUserList.value.splice(index, 1)
}

// 角色信息结果集
const roleSet = ref([])
// 请求角色信息
const getRoleInfo = () => {
    try {
        API.post('/RoleController/searchAllRole')
            .then((res) => {
                roleSet.value = res.data.data.map((item : any) => {
                    return {roleId: item.roleId, roleName: item.roleName}
                });
            })
            .catch((err) => {return err})
    } catch (error) {
        console.error('角色请求失败:', error)
    }
};

// 新增用户数据
const addUserData = {
    userAccount: '',
    userName: '',
    userPassword: '',
    userPhone: '',
    roleIdSet:[''],
    userNote: '',
    userStatus: '',
}

// 新增/编辑用户
const addEditUser = () => {
    addUserData.userAccount = ruleForm.account;
    addUserData.userName = ruleForm.name;
    addUserData.userPassword = ruleForm.password;
    addUserData.userPhone = ruleForm.phone;
    addUserData.userStatus = ruleForm.state;
    addUserData.roleIdSet = ruleForm.role;
    addUserData.userNote = ruleForm.note;
    if (addUserData.userAccount == null || addUserData.userName == null || addUserData.userStatus == null || addUserData.userPhone == null){
        ElMessage("请完善用户基础信息！（角色和备注可不填）")
    }else {
        if (submitButton.value == '新增'){
            API.post('/UserController/insertUser',addUserData)
                .then((res) => {
                    if (res.data.data == '用户添加成功'){
                        ElMessage("用户添加成功！")
                    }else {
                        ElMessage("用户添加失败！")
                    }
                })
                .catch((err) => {return err})
        }else if (submitButton.value == '编辑'){
            API.post('/UserController/editUser',addUserData)
                .then((res) => {
                    if (res.data.data == '编辑成功'){
                        ElMessage("用户编辑成功！")
                    }else {
                        ElMessage("用户编辑失败！")
                    }
                })
                .catch((err) => {return err})
        }
    }
}

// 设置提交按钮变量
let submitButton = ref('新增')
// 设置表单内容不可更改变量（默认为可见）
let inputDisabled = ref(false);
// 设置输入框label变量
let labelName = ref('创建时间');
// 设置表单title变量
let titleName = ref('表单')
// 设置新增或编辑逻辑行为判断
const controls = (control : string) => {
  if (control === 'edit'){
      dialogVisible.value = true;
      inputDisabled.value = true;
      labelName.value = '修改时间';
      titleName.value = '编辑用户';
      submitButton.value = '编辑';
  }else if(control === 'add') {
      dialogVisible.value = true;
      inputDisabled.value = false;
      labelName.value = '创建时间';
      titleName.value = '新增用户';
      submitButton.value = '新增';
  }
}

// 新增或编辑用户界面不可见
const dialogVisible = ref(false)

// 将内容填充到编辑框中
const handleEdit = (index: number, row: any) => {
    nextTick(() => {
        ruleForm.account = row.account
        ruleForm.name = row.name
        ruleForm.password = row.password
        ruleForm.phone = row.phone
        if (row.role[0] == "暂无绑定角色"){
            ruleForm.role = [];
        }else {
            ruleForm.role = row.role
        }
        if (row.note == "暂无备注"){
            ruleForm.note = '';
        }else {
            ruleForm.note = row.note;
        }
        if (row.status == '禁用'){
            ruleForm.state = "0";
        }else if (row.status == "启用"){
            ruleForm.state = "1";
        }
    })
}

interface RuleForm {
    account: string
    name: string
    password: string
    phone: string
    role: string[]
    state: string
    note: string
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    name: '',
    account: '',
    phone: '',
    role: [],
    state: '',
    note: '',
    password:'',
})

//表单校验
const rules = reactive<FormRules<RuleForm>>({
    account: [
        { required: true, message: '账号不能为空', trigger: 'blur' },
        { min: 11, max: 11, message: '账号长度为11位', trigger: 'blur' },
        { required: true, type: 'number', message: '账号只能为数字', trigger: 'blur', transform: (value) => Number(value) },
    ],
    name: [
        { required: true, message: '用户名不能为空', trigger: 'blur' },
        { min: 1, max: 5, message: '用户名长度1-5', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '密码不能为空', trigger: 'blur' },
        { min: 6, message: '密码长度不能小于6位', trigger: 'blur' },
    ],
    phone: [
        { required: true, message: '号码不能为空', trigger: 'blur' },
        { min: 11, max: 11, message: '号码长度为11位', trigger: 'blur' },
        { required: true, type: 'number', message: '账号只能为数字', trigger: 'blur', transform: (value) => Number(value) },
    ],
    role: [
        { type: 'array',required: true, message: '请至少选择一个角色', trigger: 'change' },
    ],
    state: [
        { required: true, message: '账号状态不能为空', trigger: 'change' },
    ]
})

//清空表单
const resetForm = (ruleFormRef: FormInstance | undefined) => {
    if (!ruleFormRef) return
    ruleFormRef.resetFields()
}
//查询用户
const searchData = ref({
    userAccount: '',
    userName: '',
});

const searchUserData = {
    userAccount: '',
    userName: '',
}

const searchUser = () => {
    searchUserData.userAccount = searchData.value.userAccount;
    searchUserData.userName = searchData.value.userName;
    if (searchUserData.userAccount.length == 0 && searchUserData.userName.length == 0){
        getAllUserInfo();
    }else {
        API.post("/UserController/searchUser", searchUserData)
            .then((res) => {
                allUserList.value  = res.data.data.map((item : any) => {
                    let accountStatus  = '';
                    if (item.userStatus == 0){
                        accountStatus = '禁用';
                    }else{
                        accountStatus = '启用';
                    }
                    return { account : item.userAccount, name: item.userName, phone : item.userPhone, password : item.userPassword,
                        role : item.roleNameSet, status : accountStatus, note : item.userNote}
                })
            })
            .catch((err) => {return err})
    }
}

</script>
<style>
.handle-input {
    width: 300px;
}
.mr10 {
    margin-right: 10px;
}
</style>
